package com.bobi.tfca.ui.mainnavigation.message

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bobi.tfca.R
import com.bobi.tfca.base.BaseFragment
import com.bobi.tfca.databinding.FragmentMessageBinding
import com.bobi.tfca.network.client.AppCache
import com.bobi.tfca.network.response.ChatRoomResponse
import com.bobi.tfca.ui.adapter.ChatRoomAdapter
import com.bobi.tfca.util.LogUtil


class MessageFragment : BaseFragment<FragmentMessageBinding, MessageFragmentVM>(
    FragmentMessageBinding::inflate,
    MessageFragmentVM::class.java,
    true
) {
    // 聊天室RV
    private lateinit var chatRoomRV: RecyclerView
    private lateinit var letterPanel: ImageView
    private lateinit var notificationPanel: ImageView
    private lateinit var unreadLetterDot: ImageView
    private lateinit var unreadNotificationDot: ImageView

    @SuppressLint("ResourceType", "UseRequireInsteadOfGet", "NotifyDataSetChanged")
    override fun initFragment(
        binding: FragmentMessageBinding,
        viewModel: MessageFragmentVM?,
        savedInstanceState: Bundle?
    ) {
        // 设置头部菜单的按钮
        setTopPanelStyle(binding)

        // 初始化RV
        initRecyclerView(binding)
        letterPanel = binding.letter
        notificationPanel = binding.notification
        unreadLetterDot = binding.ivLetterUnread
        unreadNotificationDot = binding.ivNotificationUnread

        // 设置viewModel的监听
        viewModel!!.apply {
            chatRooms.observe(requireActivity()) {
                val adapter: ChatRoomAdapter = chatRoomRV.adapter as ChatRoomAdapter
                adapter.setItemList(it)
                adapter.notifyDataSetChanged()
            }
        }

        publicViewModel!!.apply {
            newLetterNum.observe(this@MessageFragment) {
                LogUtil.i("newLetterNum: $it")
                if (it > 0) {
                    unreadLetterDot.visibility = View.VISIBLE
                } else {
                    unreadLetterDot.visibility = View.INVISIBLE
                }
            }

            newNotificationNum.observe(this@MessageFragment) {
                LogUtil.i("newNotificationNum: $it")
                if (it > 0) {
                    unreadNotificationDot.visibility = View.VISIBLE
                } else {
                    unreadNotificationDot.visibility = View.INVISIBLE
                }
            }
        }

        // 设置通知、信件、建群三个监听器
        setMainNavigation(binding)
    }


    /**
     * 设置通知、信件、建群三个按钮，跳转监听器
     */
    private fun setMainNavigation(binding: FragmentMessageBinding) {
        val notificationIV = binding.notification
        val letterIV = binding.letter
        val createGroupIV = binding.createGroup

        notificationIV.setOnClickListener {
            val loginStatus = AppCache.checkLoginStatus()
            if (loginStatus) {
                requireActivity().findNavController(R.id.app_nav)
                    .navigate(R.id.action_mainNavigationFragment_to_notificationFragment)
            } else {
                Toast.makeText(requireActivity(), "请登录或注册", Toast.LENGTH_SHORT).show()
            }
        }
        letterIV.setOnClickListener {
            val loginStatus = AppCache.checkLoginStatus()
            if (loginStatus) {
                requireActivity().findNavController(R.id.app_nav)
                    .navigate(R.id.action_mainNavigationFragment_to_letterFragment)
            } else {
                Toast.makeText(requireActivity(), "请登录或注册", Toast.LENGTH_SHORT).show()
            }
        }
        createGroupIV.setOnClickListener {
            val loginStatus = AppCache.checkLoginStatus()
            if (loginStatus) {
                val role = AppCache.getMyInfo().role
                // 普通会员不能创建群聊
                if ("会员".equals(role)) {
                    Toast.makeText(requireActivity(), "请联系理事创建群聊", Toast.LENGTH_SHORT)
                        .show()
                } else {
                    requireActivity().findNavController(R.id.app_nav)
                        .navigate(R.id.action_mainNavigationFragment_to_groupCreationFragment)
                }
            } else {
                Toast.makeText(requireActivity(), "请登录或注册", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 初始化RV
     */
    private fun initRecyclerView(
        binding: FragmentMessageBinding
    ) {
        // 获取聊天室RecyclerView实例
        chatRoomRV = binding.chatRoomRV

        // 获得所有聊天室
        val chatRoomList: ArrayList<ChatRoomResponse> = arrayListOf()
        // 设置布局管理器
        val linearLayoutManager = LinearLayoutManager(binding.root.context)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        chatRoomRV.layoutManager = linearLayoutManager
        chatRoomRV.addItemDecoration(
            DividerItemDecoration(
                binding.root.context,
                LinearLayoutManager.VERTICAL
            )
        )
        val chatRoomAdapter = ChatRoomAdapter(this, chatRoomList)

        // 设置群聊天室监听器
        chatRoomAdapter.setOnItemClickListener(object : ChatRoomAdapter.OnItemClickListener {
            override fun onItemClick(position: Int) {
                // 根据Int 跳转并设置对应的Fragment，携带参数
                val chatRoom = chatRoomAdapter.chatRoomList[position]
                publicViewModel!!.chatRoom.value = chatRoom
                requireActivity().findNavController(R.id.app_nav)
                    .navigate(R.id.action_mainNavigationFragment_to_groupchatRoomFragment)
            }
        })
        // 绑定Adapter
        chatRoomRV.adapter = chatRoomAdapter
    }

    /**
     * 设置顶部面板的样式
     */
    private fun setTopPanelStyle(binding: FragmentMessageBinding) {
        val topPanel = binding.topPanel
        val leftLayout = topPanel.leftLayout
        leftLayout.visibility = View.GONE
        val rightLayout = topPanel.rightLayout
        rightLayout.visibility = View.GONE
        val title = topPanel.titleText
        title.text = "消息"
    }


    /**
     * 请求数据应该在onResume生命周期
     */
    override fun resumeFragment(viewModel: MessageFragmentVM?) {
        if (AppCache.checkLoginStatus()) {
            viewModel!!.getAllChatRooms(publicViewModel!!)
            viewModel.getUnReadLetterNum(publicViewModel!!)
            viewModel.getUnReadNotificationNum(publicViewModel!!)
            publicViewModel!!.getCurrentAllMenus()
        } else {
            viewModel!!.chatRooms.value = arrayListOf()
        }
    }

}